<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gky_msg_reply".
 *
 * @property integer $id
 * @property string $reply
 * @property string $addtime
 * @property integer $msgid
 * @property integer $userid
 * 
 * @property GkyQyhUser $user
 */
class GkyMsgReply extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'gky_msg_reply';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
//            [['id'], 'required'],
            [['id', 'msgid', 'userid'], 'integer'],
            [['addtime'], 'safe'],
            [['reply'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'reply' => 'Reply',
            'addtime' => 'Addtime',
            'msgid' => 'Msgid',
            'userid' => 'Userid',
        ];
    }

    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            //添加时间
            $time = date("Y-m-d H:i:s", time());
            $this->addtime = $time;
            return true;
        } else {
            return false;
        }
    }

    public function getMsg(){

        return $this->hasOne(Msg::className(),['id'=>'msgid']);
    }

    /**
     * 获取用户
     */
    public function getQyhUser() {

        return $this->hasOne(GkyQyhUser::className(), ['id' => 'userid']);
    }

    /**
     * 获取回复内容
     * @param type $msgid
     * @param type $pageNow
     * @param type $pageSize
     * @return type
     */
    public static function getReplyList($msgid, $pageNow, $pageSize) {
        $list = GkyMsgReply::find()
                ->where(['msgid' => $msgid])
                ->addOrderBy(['addtime' => SORT_ASC])
                ->offset(($pageNow - 1) * $pageSize)
                ->limit($pageSize)
                ->all();
        $results = [];
        foreach ($list as $model) {
            $result = [
                'id' => $model->id,
                'reply' => $model->reply,
                'addtime' => $model->addtime,
                'userid' => $model->userid,
                'username' => $model->qyhUser->name,
                'avatar' => $model->qyhUser->avatar
            ];
            $results[] = $result;
        }
        return $results;
    }

}
